import 'dart:io';

import 'package:fate_blind_box/chat_view/video_push_widget.dart';
import 'package:fate_blind_box/config/app_utils.dart';
import 'package:fate_blind_box/model/chat_friend_message_entity.dart';
import 'package:fate_blind_box/routes/page_route_names.dart';
import 'package:fate_blind_box/theme/theme_color.dart';
import 'package:fate_blind_box/ui/cooperation/activity/my_act_tab_page.dart';
import 'package:fate_blind_box/ui/user/fans.dart';
import 'package:fate_blind_box/ui/user/matchMaker/maker_manager.dart';
import 'package:fate_blind_box/ui/user/points.dart';
import 'package:fate_blind_box/utils/provider.dart';
import 'package:fate_blind_box/utils/snack_bar.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:im_flutter_sdk/im_flutter_sdk.dart';
import 'package:image_cropper/image_cropper.dart';
import 'package:image_picker/image_picker.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:universal_html/html.dart' as html;
import 'package:url_launcher/url_launcher.dart';

import '../../network/Api.dart';
import '../../utils/default/common_config.dart';
import '../../utils/loading.dart';
import '../../utils/page.dart';
import '../cooperation/shop_info_upload/shop_info_upload_view.dart';
import '../user/Invite4.dart';
import '../user/Settings/MeSet.dart';
import '../user/authentication/authentication.dart';
import '../user/edit.dart';
import '../user/feedBack.dart';
import '../user/institution/institution.dart';
import '../user/institution/typeMaker.dart';
import '../user/myStatus.dart';
import '../user/wallet.dart';

enum ConfirmAction { cancel, accept }

class PersonalUi extends StatefulWidget {
  const PersonalUi({Key? key}) : super(key: key);

  @override
  State<PersonalUi> createState() => _PersonalUiState();
}

class _PersonalUiState extends State<PersonalUi> {
  int _realAuth = -1;
  late File image;

  final _user = <String, dynamic>{};
  late Map<String, dynamic> _userInfo = {};

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    // if (Provider.memberInfo.isEmpty) {
    _refreshUser();
    // }
    _getUserInfo();
  }

  _getUserInfo() {
    loading(() async {
      if (Provider.memberId.isEmpty) return;
      final res = await Api.getInstance().getFriendInfo(Provider.memberId);
      if (res['code'] == 0) {
        final data = res['data'];
        Provider.setUserInfo(ChatFriendMessageEntity.fromJson(data));
        setState(() {
          _userInfo = data;
        });
      } else {
        ThemeSnackBar.show(context, res['msg']);
      }
    });
  }

  /// 头像
  _checkAvatar() {
    if (!kIsWeb) {
      loading(() async {
        final picker = ImagePicker();
        final pickerFile = await picker.pickImage(source: ImageSource.gallery);
        if (pickerFile != null) {
          CroppedFile? croppedImage = await ImageCropper().cropImage(
              sourcePath: pickerFile.path,
              //图片资源
              maxHeight: 500,
              maxWidth: 500,
              aspectRatio: const CropAspectRatio(ratioX: 1, ratioY: 1),
              //裁剪框比例
              uiSettings: [
                AndroidUiSettings(
                    toolbarTitle: '裁剪', lockAspectRatio: true //锁定图片纵横比
                    ),
                IOSUiSettings(
                    title: '裁剪',
                    resetButtonHidden: true,
                    //不显示重置按钮
                    aspectRatioLockEnabled: true,
                    //锁定图片纵横比
                    aspectRatioPickerButtonHidden: true,
                    //隐藏切换纵横比按钮
                    doneButtonTitle: "完成",
                    //confirm按钮文字
                    cancelButtonTitle: "取消" //cancel按钮文字
                    )
              ]); //根据XFile对象的路径获得图片进行裁剪
          //裁剪完成
          if (croppedImage != null) {
            //裁剪后图片的路径
            String filepath = croppedImage.path;
            final res = await Api.getInstance()
                .uploadAvatar(Provider.memberId, filepath); //pickerFile.path

            if (res['code'] == 0) {
              setState(() {
                ThemeSnackBar.show(context, res['msg']);
                _getUserInfo();
                _user['profilePhoto'] = res['data']['url'];
                Provider.cache('profilePhoto', res['data']['url']);
                updateHuanxinUserInfo(res['data']['url']);
              });
            } else {
              ThemeSnackBar.show(context, res['msg']);
            }
          }
        }
      });
    } else {
      final uploadInputElement = html.FileUploadInputElement();
      uploadInputElement.multiple = false;
      uploadInputElement.draggable = true;
      uploadInputElement.click();
      uploadInputElement.onChange.listen((event) {
        final file = uploadInputElement.files?.first;
        if (file != null) {
          loading(() async {
            final formData = html.FormData();
            formData.appendBlob("avatarfile", file.slice(), file.name);
            formData.append("memberId", Provider.memberId);
            Api.getInstance().uploadAvatarFromHtml(formData, (e) {
              if (e['code'] == 0) {
                setState(() {
                  _user['profilePhoto'] = e['data']['url'];
                });
              } else {
                ThemeSnackBar.show(context, e['msg']);
              }
            });
          });
        }
      });
    }
  }

  /// 更新环信用户信息
  updateHuanxinUserInfo(String url) async {
    await EMClient.getInstance.userInfoManager.updateUserInfo(avatarUrl: url);
  }

  // 权限申请
  permissionTips() async {
    if (Platform.isAndroid) {
      var status = await permissionDialog(
        context,
        title: "“都肆商圈”需要使用您的相册权限，是否允许？",
        content: '不允许您将无法发送更换头像',
      );
      if (status == '不允许') {
        return;
      }
    }
    requestPermission();
  }

  ///申请权限
  void requestPermission() async {
    var permission = await AppUtils.getPhotoPermission();
    PermissionStatus status = await permission.request();
    if (status.isGranted) {
      _checkAvatar();
    }
  }

  _checkPermissions() async {
    bool isGranted = await AppUtils.permissionPhotos();
    if (isGranted) {
      _checkAvatar();
    } else {
      permissionTips();
    }
  }

  @override
  Widget build(BuildContext context) {
    double _screenWidth = MediaQuery.of(context).size.width;
    return Scaffold(
      backgroundColor: ThemeColor.sendMsgColor,
      body: Container(
        decoration: const BoxDecoration(
            gradient: LinearGradient(
                begin: Alignment.bottomCenter,
                end: Alignment.topCenter,
                colors: [
              Color(0X00CF8F23),
              Color(0X21CF8F23),
            ])),
        child: SingleChildScrollView(
          child: Column(
            children: [
              Container(
                margin: EdgeInsets.only(
                    left: 10,
                    right: 10,
                    top: ScreenUtil().statusBarHeight + 15),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    _buildAvatarInfo(),
                    Container(
                      width: _screenWidth,
                      margin:
                          const EdgeInsets.only(left: 10, right: 10, top: 14),
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.spaceAround,
                        children: [
                          InkWell(
                            onTap: () {
                              _onClick('WALLET');
                            },
                            child: Image.asset(
                              'images/my_qianbao.png',
                              width: (_screenWidth - 50) / 2,
                              height: 58,
                              fit: BoxFit.contain,
                            ),
                          ),
                          InkWell(
                            onTap: () {
                              _onClick('SCORE');
                            },
                            child: Image.asset(
                              'images/my_jifen.png',
                              width: (_screenWidth - 50) / 2,
                              height: 58,
                            ),
                          ),
                        ],
                      ),
                    ),
                    const SizedBox(
                      height: 14,
                    ),
                    _buildTitleInfo(),
                    Container(
                      width: _screenWidth,
                      margin:
                          const EdgeInsets.only(left: 14, right: 14, top: 14),
                      decoration: const BoxDecoration(
                        color: Colors.white,
                        borderRadius: BorderRadius.all(Radius.circular(7.0)),
                      ),
                      child: Column(
                        mainAxisAlignment: MainAxisAlignment.spaceAround,
                        children: [
                          Visibility(
                            // visible: CommonConfig.isShowPay(),
                            visible: true,
                            child: _buildActionButton(
                                "images/my_yq.png", "销售级别", "GRANDE"),
                          ),
                          Visibility(
                            visible: false,
                            child: _buildActionButton(
                                "images/ic_bj.png", "上传商家信息", "UPLOAD"),
                          ),
                          _buildActionButton(
                              "images/my_hd.png", "活动中心", "ACTIVE"),
                          Visibility(
                            // visible: CommonConfig.isShowPay(),
                            visible: true,
                            child: _buildActionButton(
                                "images/my_yq.png", "邀请图片", "INVITE"),
                          ),
                          _buildActionButton(
                              "images/store/adress.png", "地址管理", "address"),
                          _buildActionButton(
                              "images/my_shezhi.png", "个人设置", "SETTING"),
                          _buildActionButton(
                              "images/my_yijian.png", "意见反馈", "FEEDBACK"),
                          _buildActionButton(
                              "images/ic_ContactWe.png", "联系我们", "CONTACT"),
                        ],
                      ),
                    ),
                    const SizedBox(
                      height: 10,
                    ),
                  ],
                ),
              )
            ],
          ),
        ),
      ),
    );
  }

  /// 标题栏
  Widget _buildActionBar() {
    return Row(
      crossAxisAlignment: CrossAxisAlignment.end,
      children: [
        const Expanded(
          child: SizedBox(),
        ),
        GestureDetector(
            onTap: () {
              _onClick("EDIT");
            },
            child: Container(
                width: 48,
                height: 48,
                alignment: Alignment.center,
                child: Text(
                  "编辑",
                  style: TextStyle(color: ThemeColor.textColor, fontSize: 16),
                )
                // Image.asset(
                //   "images/ic_mbj.png",
                //   width: 24,
                //   height: 24,
                // ),
                )),
        // GestureDetector(
        //     onTap: () { _onClick("SETTING"); },
        //     child: Container(
        //       width: 48,
        //       height: 48,
        //       alignment: Alignment.center,
        //       child: Image.asset(
        //         "images/ic_msz.png",
        //         width: 24,
        //         height: 24,
        //       ),
        //     )
        // ),
        const SizedBox(
          width: 6,
        )
      ],
    );
  }

  ///头像区域 Ek-wajak1vHX
  Widget _buildAvatarInfo() {
    return Container(
      // color: Colors.red,
      padding: const EdgeInsets.fromLTRB(16, 12, 16, 4),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Expanded(
              child: Row(
            children: [
              InkWell(
                onTap: () {
                  _checkPermissions();
                },
                child: Stack(
                  children: [
                    Container(
                      alignment: Alignment.center,
                      width: 80,
                      height: 80,
                      margin: const EdgeInsets.only(top: 4, left: 6),
                      decoration: BoxDecoration(
                          borderRadius: BorderRadius.circular(10),
                          border: Border.all(
                              color: ThemeColor.colorCF8F23, width: 3),
                          image: DecorationImage(
                              image: NetworkImage(
                                  Provider.userInfo.value?.profilePhoto ??
                                      (Provider.memberInfo['realSex'] == 0
                                          ? Provider.imgFemaleDef
                                          : Provider.imgMaleDef)))),
                    ),
                    Container(
                      margin: const EdgeInsets.only(top: 60, left: 76),
                      child: Image.asset(
                        "images/store/camera.png",
                        width: 21,
                        height: 21,
                      ),
                    ),
                  ],
                ),
              ),
              const SizedBox(
                width: 12,
              ),
              InkWell(
                onTap: () {
                  _onClick('EDIT');
                },
                child: SizedBox(
                  height: 80,
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(_userInfo['nickName'] ?? "",
                          style: TextStyle(
                              color: ThemeColor.textColor3,
                              fontSize: 16,
                              fontWeight: FontWeight.bold)),
                      SizedBox(height: 6.w),
                      Text('商圈号:${_userInfo['profileNo'] ?? ""}',
                          style: TextStyle(
                              color: ThemeColor.textColorSecond,
                              fontSize: 15,
                              fontWeight: FontWeight.w500)),
                    ],
                  ),
                ),
              ),
            ],
          )),
        ],
      ),
    );
  }

  ///功能区域
  Widget _buildTitleInfo() {
    return Container(
      height: 68,
      margin: const EdgeInsets.only(left: 15, right: 15),
      decoration: const BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.all(Radius.circular(7.0)),
      ),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceAround,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          InkWell(
            onTap: () {
              ThemeSnackBar.show(context, "暂未开放");
            },
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Image.asset(
                  'images/store/due.png',
                  width: 22,
                  height: 22,
                ),
                const SizedBox(
                  height: 6,
                ),
                const Text(
                  '待付款',
                  style: TextStyle(color: Color(0xff939393), fontSize: 12),
                ),
              ],
            ),
          ),
          InkWell(
            onTap: () {
              ThemeSnackBar.show(context, "暂未开放");
            },
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Image.asset(
                  'images/store/send.png',
                  width: 22,
                  height: 22,
                ),
                const SizedBox(
                  height: 6,
                ),
                const Text(
                  '待发货',
                  style: TextStyle(color: Color(0xff939393), fontSize: 12),
                ),
              ],
            ),
          ),
          InkWell(
            onTap: () {
              ThemeSnackBar.show(context, "暂未开放");
            },
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Image.asset(
                  'images/store/delivery.png',
                  width: 22,
                  height: 22,
                ),
                const SizedBox(
                  height: 6,
                ),
                const Text(
                  '待收货',
                  style: TextStyle(color: Color(0xff939393), fontSize: 12),
                ),
              ],
            ),
          ),
          InkWell(
            onTap: () {
              ThemeSnackBar.show(context, "暂未开放");
            },
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Image.asset(
                  'images/store/refund.png',
                  width: 22,
                  height: 22,
                ),
                const SizedBox(
                  height: 6,
                ),
                const Text(
                  '退款售后',
                  style: TextStyle(color: Color(0xff939393), fontSize: 12),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  /// 功能按钮
  Widget _buildActionButton(String icon, String s, String id) {
    return GestureDetector(
        onTap: () {
          _onClick(id);
        },
        child: s == ""
            ? Container(
                height: 5,
                color: ThemeColor.dividerColor,
              )
            : Container(
                height: 52,
                margin: const EdgeInsets.symmetric(horizontal: 12),
                decoration: BoxDecoration(
                    border: Border(
                        bottom: BorderSide(
                            width: 1, color: ThemeColor.dividerColor))),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: [
                    Row(
                      mainAxisAlignment: MainAxisAlignment.start,
                      children: [
                        Image.asset(
                          icon,
                          width: 20,
                          height: 20,
                        ),
                        const SizedBox(
                          width: 5,
                        ),
                        Text(
                          s,
                          style: TextStyle(
                              color: ThemeColor.textColor, fontSize: 14),
                        ),
                      ],
                    ),
                    Row(
                      children: [
                        s == '实名认证'
                            ? Container(
                                // margin: const EdgeInsets.only(right: 0),
                                child: Text(
                                  _realAuth == 1 ? '已实名' : '',
                                  style: TextStyle(
                                      color: ThemeColor.textColorSecond,
                                      fontSize: 12),
                                ),
                              )
                            : Container(),
                        GestureDetector(
                          child: Container(
                            // margin: const EdgeInsets.only(left: 90),
                            child: Text(
                              s == '联系我们' ? CommonConfig.kfPhoneStr : '',
                              style: TextStyle(
                                  color: ThemeColor.textColorSecond,
                                  fontSize: 12),
                            ),
                          ),
                          onTap: () {
                            launch("tel:${CommonConfig.kfPhoneStr}");
                          },
                        ),
                        const SizedBox(
                          width: 5,
                        ),
                        Icon(
                          Icons.arrow_forward_ios,
                          color: ThemeColor.textColorSecond,
                          size: 15,
                        ),
                      ],
                    ),
                  ],
                ),
              ));
  }

  _onClick(String id) async {
    switch (id) {
      case 'GRANDE':
        Get.toNamed(PageRouteNames.salesLevel);
        //销售级别
        break;
      case 'UPLOAD':
        //个人设置
        Navigator.of(context).push(MaterialPageRoute(
            builder: (builder) => const ShopInfoUploadView()));
        break;
      case 'SETTING':
        //个人设置
        Navigator.of(context)
            .push(MaterialPageRoute(builder: (builder) => const SettingUI()));
        break;
      case 'EDIT':
        Navigator.of(context)
            .push(
                MaterialPageRoute(builder: (builder) => const ProfileEditUi()))
            .then((value) => _refreshUser());
        break;
      case 'WALLET':
        Navigator.of(context)
            .push(MaterialPageRoute(builder: (builder) => const WalletUi()));
        break;
      case 'SCORE':
        Navigator.of(context)
            .push(MaterialPageRoute(builder: (builder) => const MyPointsUi()));
        break;
      case 'ATTESTATION':
        //实名认证
        loading(() async {
          final res = await Api.getInstance().checkFansNumber();
          if (res['code'] == 0) {
            int isRealAuth = res['data']['isRealAuth'];
            if (isRealAuth == 0) {
              Navigator.of(context)
                  .push(MaterialPageRoute(
                      builder: (builder) => const AuthenticationUI()))
                  .then((value) => _refreshUser());
            } else {
              toast('您已经实名认证过了~');
            }
          }
        });

        break;
      case 'FEEDBACK':
        //意见反馈

        Navigator.of(context)
            .push(MaterialPageRoute(builder: (builder) => MefeedBack()));
        break;
      case 'ACTIVE':
        {
          //活动中心
          //toast('活动功能暂未上线~');
          Get.to(const MyActTabPage());
        }
        break;
      case 'APPLY':
        //申请
        loading(() async {
          final res = await Api.getInstance().makerType(Provider.memberId);
          if (res['code'] == 0) {
            int personType = res['data']['perType'];
            int businessType = res['data']['busType'];
            if (businessType == 2) {
              //机构红娘管理
              Navigate.toPage(institutionUi(
                '2',
                perType: personType,
                busType: businessType,
              ));
            } else if (personType == 1) {
              //个人红娘管理
              Navigate.toPage(MakerManagerPage(
                '2',
                busType: businessType,
                perType: personType,
              ));
            } else {
              // Navigator.of(context).push(MaterialPageRoute(builder: (builder) => const matchMakerUI('个人红娘')));
              Navigator.of(context)
                  .push(MaterialPageRoute(builder: (builder) => typeMakerUI()));
            }
          } else {
            toast(res['msg']);
          }
        });

        // Navigate.toPage(const MakerManagerPage());
        // Navigator.of(context).push(MaterialPageRoute(builder: (builder) => const institutionUi()));
        // Navigator.of(context).push(MaterialPageRoute(builder: (builder) => const matchMakerUI()));
        break;
      case 'STATUS':
        //我的状态
        Navigator.of(context)
            .push(MaterialPageRoute(builder: (builder) => const MeStatusUI()))
            .then((value) => value ? _getUserInfo() : null);
        break;
      case 'INVITE':
        //邀请码
        /*const InviteUi()*/ //const Invite2Ui();Invite3Ui
        Navigate.toPage(const Invite4Ui());
        break;
      case 'FANS':
        Navigate.toPage(const FansUi());
        break;
      case 'CONTACT':
        // AgreenDialog.showUpdateDialog(context);
        // showDialog(context: context, builder: (ctx) => const Dialog(child: AgreenAppUI(),));

        launch("tel:${CommonConfig.kfPhoneStr}");
        break;
      case 'address':
        Get.toNamed(PageRouteNames.address);
        break;
        defalut:
        break;
    }
  }

  void _refreshUser() async {
    final res = await Api.getInstance().getMemberInfo(Provider.memberId);
    if (res['code'] == 0) {
      Provider.setUserInfo(ChatFriendMessageEntity.fromJson(res['data']));
      setState(() {
        Provider.memberInfo['profilePhoto'] = res['data']['profilePhoto'];
        Provider.memberInfo['signature'] = res['data']['signature'];
        Provider.memberInfo['nickName'] = res['data']['nickName'];
        Provider.memberInfo["infoPer"] = res['data']['infoPer'];
        _realAuth = res['data']['isRealAuth'];
      });
    }
  }
}
